//
//  PublishViewController.swift
//  BaseSwift
//
//  Created by gh on 2019/10/11.
//  Copyright © 2019 ghwang. All rights reserved.
//

import UIKit
struct UploadImageVo {
    
    var image: UIImage?
    var id: Int?
    private var imgUrls: Array<String> = [String]()

}

class PublishViewController: UIViewController {

    let inputV = GCPlaceholderTextView()
    let inputContV = GCPlaceholderTextView()
    let inputBg = UIView()
    
    private var imgBgScr: UIScrollView? = UIScrollView()
    private var imgArr: Array<UploadImageVo>? = [UploadImageVo]()
    private var imgContainerView: UIView?

    private var tits: Array<String> = [String]()
    private var imgUrls: Array<String> = [String]()


    lazy var titView:UIView = {
        
        let bg = UIView()
        bg.backgroundColor = UIColor.white
        bg.addSubview(self.inputV)
        self.inputV.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight(rawValue: 0.2))
        self.inputV.textColor = UIColor.textTitleColorBlack
        self.inputV.placeholder = "帖子的主题"
        self.inputV.placeholderColor = UIColor.textPlaceHolderColor
        let _ = self.inputV.sd_layout()?.leftSpaceToView(bg,16)!.rightSpaceToView(bg,16)!.heightIs(50)!.centerYEqualToView(bg)
        //self.inputV.becomeFirstResponder()
        
        
        return bg
        
    }()
    lazy var navView:UIView = {
        
        let bg = UIView()
        bg.backgroundColor = UIColor.white
        bg.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: HT_StatusBarAndNavigationBarHeight)
        let cancelBtn = UIButton()
        cancelBtn.setTitle("取消", for: .normal)
        cancelBtn.addTarget(self, action: #selector(cancelBtnClick), for: .touchUpInside)
        cancelBtn.setTitleColor(UIColor.textTitleColor, for: .normal)
        cancelBtn.titleLabel?.font = UIFont.commonFontSmaller
        bg.addSubview(cancelBtn)
        let _ = cancelBtn.sd_layout()?.leftSpaceToView(bg,16)!.heightIs(28)!.widthIs(38)!.topSpaceToView(bg,HT_StatusBarHeight+5)

        
        let titLab = UILabel()
        titLab.font = UIFont.titleFont
        titLab.text = "发帖"
        titLab.textColor = UIColor.black
        bg.addSubview(titLab)
        titLab.textAlignment = .center
        let _ = titLab.sd_layout()?.widthIs(60)!.heightIs(20)!.centerXEqualToView(bg)!.topSpaceToView(bg,HT_StatusBarHeight+5)

        
        
        let pubBtn = UIButton()
        bg.addSubview(pubBtn)
        let _ = pubBtn.sd_layout()?.widthIs(64)!.heightIs(28)!.topSpaceToView(bg,HT_StatusBarHeight+5)!.rightSpaceToView(bg,16)
        pubBtn.setTitle("发布", for: .normal)
        pubBtn.setTitleColor(UIColor.white, for: .normal)
        pubBtn.sd_cornerRadius = 14
        pubBtn.titleLabel?.font = UIFont.commonFontSmaller

        pubBtn.addTarget(self, action: #selector(pubBtnClick), for: .touchUpInside)
        pubBtn.gradientBtnMainColor()
        pubBtn.bringSubviewToFront(pubBtn.titleLabel!)
        
        
        
        return bg
    }()
    
    @objc func cancelBtnClick(){
        
        POP(vc: self)
    }
    @objc func pubBtnClick(){
        
        self.publishClick()
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.view.backgroundColor = UIColor.backgroundColor
        self.view.addSubview(self.navView)
        
        
        
//        self.navigationView.addLeftButton(withTitle: "取消") { (view) in
//
//            POP(vc: self)
//        }
//
//        self.navigationView.addRightButton(withTitle: "发布") { (view) in
//
//            self.publishClick()
//        }
        
        
        view.addSubview(titView)
        let _ = titView.sd_layout()?.widthRatioToView(view,1)!.heightIs(64)!.topSpaceToView(view,HT_StatusBarAndNavigationBarHeight)
        
        inputBg.backgroundColor = UIColor.white
        view.addSubview(inputBg)
        let _ = inputBg.sd_layout()?.widthRatioToView(view,1)!.topSpaceToView(titView,0)!.heightIs(150)
        
        inputBg.addSubview(inputContV)
        self.inputContV.font = UIFont.commonFont
        self.inputContV.textColor = UIColor.textTitleColorBlack
        self.inputContV.placeholder = "帖子的详细内容"
        self.inputContV.placeholderColor = UIColor.textPlaceHolderColor
        let _ = self.inputContV.sd_layout()?.leftSpaceToView(inputBg,16)!.rightSpaceToView(inputBg,16)!.heightIs(135)!.centerYEqualToView(inputBg)
        
        let imgBgV = self.reloadImages()
        view.addSubview(imgBgV)
        imgBgV.backgroundColor = UIColor.white
        let _ = imgBgV.sd_layout()?.leftSpaceToView(view,0)!.topSpaceToView(self.inputBg,0)!.heightIs(195)!.rightSpaceToView(view,0)
        
        
        
    }
    
       func reloadImages() -> UIScrollView{
           

           if imgBgScr==nil{
               
               imgBgScr = UIScrollView()
            }
           
           if imgArr!.count < 6{
               
               var addVo = UploadImageVo()
               addVo.id = -1
               imgArr?.append(addVo)
           }
           if imgContainerView != nil {
               
               imgContainerView?.removeFromSuperview()
           }
           imgContainerView = UIView()
           imgBgScr!.addSubview(imgContainerView!)
           var temp = Array<UIView>()
           
           for index in 0 ..< imgArr!.count {
               
               var up: UploadImageVo = imgArr![index]
    
               let menuBtn = UIButton()
               menuBtn.tag = 10086+index
               if up.id == -1{
                   
                   up.image = UIImage(named: "add")
                   menuBtn.addTarget(self, action: #selector(addClick), for: .touchUpInside)
                   
               }else{
                   
                   let delIcon = UIImageView()
                   delIcon.image = UIImage(named: "清除1")
                   menuBtn.addSubview(delIcon)
                   _ = delIcon.sd_layout()?.widthIs(18)?.heightIs(18)?.topSpaceToView(menuBtn,0)?.rightSpaceToView(menuBtn,0)
                   menuBtn.addTarget(self, action: #selector(delImageClick), for: .touchUpInside)

                   
               }
               menuBtn.setImage(up.image, for: .normal)
               imgContainerView!.addSubview(menuBtn)
               let _ = menuBtn.sd_layout()?.heightIs(68)
               
               
           
               temp.append(menuBtn)
               
           }
           let _ = imgContainerView!.sd_layout()?.topSpaceToView(imgBgScr,16)?.widthRatioToView(imgBgScr,1)
           
           imgContainerView!.setupAutoWidthFlowItems(temp, withPerRowItemsCount: 4, verticalMargin: 16, horizontalMargin: 10, verticalEdgeInset: 0, horizontalEdgeInset: 16)
           
           imgBgScr!.setupAutoContentSize(withBottomView: imgContainerView!, bottomMargin: 0)
           
           return imgBgScr!
           
       }

    @objc func addClick(){
        
        let imgPicker = MLImagePickerViewController.init()
        imgPicker.maxCount = 6
        imgPicker.assetsFilter = .allPhotos
        imgPicker.display(forVC: self) { (success, urls, thumbImages, originalImages, error) in
            
            if success && thumbImages?.count ?? 0 > 0{
                
                self.configPhoto(thumbImages: thumbImages ?? [UIImage](), originImages: originalImages ?? [UIImage]())
            }
        }
        
    }
    
    @objc func delImageClick(btn: UIButton){
        
        let index: Int = btn.tag - 10086
        imgArr?.remove(at: index)
        if index == 5 {
            
        }else{
            
            _ = imgArr?.popLast()

        }
        _ = reloadImages()
    }
    
    func configPhoto(thumbImages: Array<UIImage>,originImages: Array<UIImage>){
        
        _ = imgArr?.popLast()
        for item in originImages{
            var upVo = UploadImageVo()
            upVo.image = item
            imgArr?.append(upVo)
        }
        _ = reloadImages()
    }
    
    func publishClick() {
        
        
        if inputV.text.isEmpty == true {
            
            ToastUtil.show(msg: "请输入标题")
            return
        }

        //先上传图片
        _ = imgArr?.popLast()
        let tempimgs = imgArr
        //没有图片
        if (tempimgs?.count)! == 0{
            
            self.commitData()
            return
        }
        SVProgressHUD.show()
        SVProgressHUD.setDefaultStyle(.dark)
        SVProgressHUD.setDefaultAnimationType(.flat)
        for item in tempimgs!{
             
            let str0 = NSDate.br_getString(Date(), format: "yyyyMMddHHmmss")
            let str1 = (arc4random()%100000+1).description
            let str2 = String(format: "%@%@", str0!,str1).toBase64()
            
            BZHttpFileHelper.fileHelperShareInstance().uploadAmr((item.image?.zipMaxSizeImage())!, amrName: str2!+".png") { (url) in
                
                self.imgUrls.append(url as! String)
                if self.imgUrls.count == tempimgs?.count{
                    
                    self.commitData()
                }
                
                
                
            }
             
         }

    }
    func commitData(){
        
        var urls = ""
        if self.imgUrls.count>0 {
            
            for item in self.imgUrls{
                
                urls += item+","
            }
        }
        if urls.count == 0{
            
            urls = ","
        }
        
//        DispatchQueue.main.async(execute: {
//
//            let img = self.imgArr?.first
//            let vc = TestTopViewController()
//            vc.img = UIImage(data: (img?.image?.zipMaxSizeImage())!)
//            PUSH(from: self, to: vc)
//            return
//        })


        if inputContV.text.count == 0 {
            
            inputContV.text = ""
        }
        
        API.publishSocial(params: [
                                   "content":inputContV.text!,
                                   "title":inputV.text!,
                                   "imgList":urls.subString(start: 0, length: urls.count-1)]) { (result) in
            
                                    ToastUtil.show(msg: "发布成功,请耐心等待审核")
                                    POP(vc: self)
        }
        
    }
    
   


}
